package com.ITXu.reggie.service.serviceImpl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ITXu.reggie.DTO.SetmealDto;
import com.ITXu.reggie.commom.CustomException;
import com.ITXu.reggie.entity.DishFlavor;
import com.ITXu.reggie.entity.Setmeal;
import com.ITXu.reggie.entity.SetmealDish;
import com.ITXu.reggie.mapper.SetmealMapper;
import com.ITXu.reggie.service.SetmealDishService;
import com.ITXu.reggie.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

@Service
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService{

	@Autowired
	private SetmealDishService setmealDishService;
	
	@Override
	public void saveWithDish(SetmealDto setmealDto) {
		//保存setmeal
		this.save(setmealDto);
		//保存setmeal_dish
		List<SetmealDish> setmealdishes = setmealDto.getSetmealDishes();
		setmealdishes.stream().map((item) -> {
			Long setmealId = setmealDto.getId();
			item.setSetmealId(setmealId);
			return item;
		}).collect(Collectors.toList());
		setmealDishService.saveBatch(setmealdishes);
	}

	@Override
	public void updateWithDish(SetmealDto setmealDto) {
		//更新setmeal
		this.updateById(setmealDto);
		//删除原先的setmealdish集合
		Long setmealId = setmealDto.getId();
		LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(SetmealDish::getSetmealId, setmealId);
		setmealDishService.remove(queryWrapper);
		//新增一个setmealdish集合
		List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
		for (SetmealDish setmealDish : setmealDishes) {
			setmealDish.setSetmealId(setmealId);
		}
		setmealDishService.saveBatch(setmealDishes);
	}

	@Override
	public void removeWithDish(List<Long> ids) {
		//判断status是否等于1，如果等于1，抛出业务异常（“当前套餐正在出售中，无法删除！”）
		LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(Setmeal::getId, ids);
		queryWrapper.eq(Setmeal::getStatus, 1);
		int count = this.count(queryWrapper);
		if (count>0) {
			throw new CustomException("当前套餐正在出售中，无法删除！");
		}
		//删除相关setmeal
		this.removeByIds(ids);
		//删除相关setmealdish
		LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
		setmealDishService.remove(lambdaQueryWrapper);
	}

}
